#include "common_opr_all.h"
#include <chrono>
#include <sys/time.h>

CommonOprTime::CommonOprTime()
{
}

CommonOprTime::~CommonOprTime()
{
}

uint64_t CommonOprTime::getTime()//ms
{
    return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}

string CommonOprTime::getTimestr()
{
    uint64_t vCurTimeMs = getTime();
    string timestr;
    timestr = to_string(vCurTimeMs);
    return timestr;
}

double CommonOprTime::getMsTime()
{
    timespec timespecStart_;
    timeval timeStart_;
    gettimeofday(&timeStart_, NULL);
    clock_gettime(CLOCK_THREAD_CPUTIME_ID, &timespecStart_);
    double dtime_ = timeStart_.tv_sec + timeStart_.tv_usec / static_cast<double>(1e6);
    return dtime_ * 1000.0;
}

uint64_t CommonOprTime::getTimeUTC8(const uint64_t &recordTime)
{
    uint64_t curTimeUTC = recordTime;
    uint64_t timeInterval = (uint64_t)(8 * 60 * 60 * 1000);
    uint64_t curTimeUTC8 = curTimeUTC + timeInterval;

    return curTimeUTC8;
}

string CommonOprTime::getDateUTC8str(const uint64_t &recordTime)
{
    uint64_t curTimeUTC8 = getTimeUTC8(recordTime);
    auto curTimeMs = std::chrono::milliseconds(curTimeUTC8);
    auto curTimePoint = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(curTimeMs);
    auto curTimeT = std::chrono::system_clock::to_time_t(curTimePoint);
    std::tm* curTime = std::gmtime(&curTimeT);
    std::string curTimeStr;
    if (curTime != NULL)
    {
        std::string year = std::to_string(curTime->tm_year + 1900);

        std::string mon = timeIntToString(curTime->tm_mon + 1);
        std::string day = timeIntToString(curTime->tm_mday);
        std::string hour = timeIntToString(curTime->tm_hour);
        std::string min = timeIntToString(curTime->tm_min);
        std::string sec = timeIntToString(curTime->tm_sec);

        curTimeStr = year + mon + day + hour + min + sec;
    }
    return curTimeStr;
}

string CommonOprTime::timeIntToString(int time)
{
    std::string timeStr;
    char str[10];
    sprintf(str, "%02u", time);

    timeStr = str;
    
    return timeStr;
}